<template>
  <div id="CreateBlog">
    <h1 style="font-size: 30px;margin-bottom:10px">创建Blog</h1>
    <el-row :gutter="20">
      <el-col :span="18">
        <el-input
          v-model="blog.title"
          placeholder="请输入标题"
          maxlength="20"
          show-word-limit
        ></el-input>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="$save">保存</el-button>

        <el-dialog title="保存Blog" :visible.sync="dialogFormVisible">
          <form name="form">
            <p>请选择Blog类型</p>
            <el-radio-group v-model="classifId">
              <el-radio
                :label="c.classifyId"
                v-for="c in classifies"
                :key="c.classifyId"
              >
                <span>{{ c.classifyName }}</span>
              </el-radio>
            </el-radio-group>
            <p>请选择Blog标签</p>
            <el-checkbox-group v-model="tagIdList">
              <el-checkbox v-for="t in tags" :key="t.tagId" :label="t.tagId">{{
                t.tagName
              }}</el-checkbox>
            </el-checkbox-group>

            <p>请选择Blog封面</p>
            <el-upload
              class="upload-demo"
              :limit="1"
              :file-list="fileList"
              :action="path"
              name="blogimg"
              :on-success="handleSuccess"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
            >
              <el-button
                type="primary"
                size="small"
                style="transform: translateX(-50px)"
                >点击上传
              </el-button>
              <div solt="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不能超过3M
              </div>
            </el-upload>
          </form>
          <el-row class="btngroup">
            <el-button @click="saveToDraft" type="info"
              >保存放入草稿箱</el-button
            >
            <el-button @click="saveAndPublish">保存并发布</el-button>
          </el-row>
        </el-dialog>
      </el-col>
    </el-row>

    <mavon-editor
      :ishljs="true"
      style="height:600px; margin-top: 20px"
      fontSize="17px"
      ref="md"
      @imgAdd="$ImgAdd"
      @save="$save"
      v-model="blog.content"
      @imgDel="$ImgDel"
    >
    </mavon-editor>
  </div>
</template>

<script>

export default {
  name: "CreateBlog",
  data() {
    return {
      path: this.axios.defaults.baseURL + "/blog/upload/cover",
      dialogFormVisible: false,
      blog: {
        title: "",
        content: "",
        readCount: 0,
        isDraft: 0,
        blogCover: "",
        userId: 0,
      },
      tags: [],
      tagIdList: [],
      classifies: [],
      classifId: "",
      fileList: [],
    };
  },
  methods: {
    $ImgAdd(pos, $file) {
      var formdata = new FormData();
      formdata.append("image", $file);
      this.axios.post("/blog/upload/img", formdata).then((res) => {
        if (res.status == 200) {
          this.$message.success("上传成功");
          this.$refs.md.$img2Url(pos, res.data.url);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    $ImgDel(pos, $file) {
      let webrootlen = this.axios.defaults.baseURL.length;
      let path = pos[0].substring(webrootlen);
      let formdata = new FormData();
      formdata.append("imgPath", path);
      this.axios.post("/blog/remove/img", formdata).then((res) => {
        if (res.data.success) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    $save() {
      this.dialogFormVisible = true;
    },
    loadTagList() {
      this.axios.get("/tag/select").then((res) => {
        this.tags = res.data.data;
      });
    },
    loadClassify() {
      this.axios.get("/classify/select").then((res) => {
        this.classifies = res.data.data;
      });
    },
    handleSuccess(res) {
      if (res.success) {
        this.$message.success(res.msg);
        this.blog.blogCover = res.path;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前只能选择1个图片文件，本次选择了${files.length}个文件，共选择了${
          files.length + fileList.length
        }个文件`
      );
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isJPG) {
        this.$message.error("上传封面文件只能是JPG/PNG格式");
      }
      if (!isLt3M) {
        this.$message.error("上传封面文件大小不能超过3MB");
      }
      return isJPG && isLt3M;
    },
    beforeRemove(file) {
      return this.$confirm(`确认移除${file.name}？`);
    },
    handleRemove(file) {
      let formdata = new FormData();
      formdata.append("imgPath", file.response.path);
      this.axios.post("/blog/remove/img", formdata).then((res) => {
        if (res.data.success) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
      this.blog.blogCover = "";
    },
    saveToDraft() {
      this.blog.isDraft = 1;
      let formdata = new FormData();
      formdata.append("title", this.blog.title);
      formdata.append("content", this.blog.content);
      formdata.append("userId", this.blog.userId);
      formdata.append("blogCover", this.blog.blogCover);
      formdata.append("isDraft", this.blog.isDraft);
      formdata.append("classifyId", this.classifId);
      formdata.append("tags", this.tagIdList);
      if (this.classifId == "" || this.tagIdList.length == 0) {
        this.$message.error("请选择标签和分类");
      } else {
        this.axios.post("/blog/add", formdata).then((res) => {
          if (res.data.success) {
            this.$message.success("保存成功，已放入草稿箱");
            this.dialogFormVisible = false;
            this.$router.push("../draft");
          } else {
            this.$message.error(res.data.msg);
          }
        });
      }
    },
    saveAndPublish() {
      let formdata = new FormData();
      formdata.append("title", this.blog.title);
      formdata.append("content", this.blog.content);
      formdata.append("userId", this.blog.userId);
      formdata.append("blogCover", this.blog.blogCover);
      formdata.append("isDraft", this.blog.isDraft);
      formdata.append("classifyId", this.classifId);
      formdata.append("tags", this.tagIdList);
      if (this.classifId == "" || this.tagIdList.length == 0) {
        this.$message.error("请选择标签和分类");
      } else {
        this.axios.post("/blog/add", formdata).then((res) => {
          if (res.data.success) {
            this.$message.success("发布成功");
            this.dialogFormVisible = false;
            this.$router.push("./BlogList");
          } else {
            this.$message.error("发布失败");
          }
        });
      }
    },
  },
  created() {
    this.loadTagList();
    this.loadClassify();
    this.blog.userId = JSON.parse(localStorage.getItem("access-User")).userId;
  },
};
</script>

<style>
#CreateBlog .btngroup {
  text-align: center;
  margin-top: 20px;
}

#CreateBlog .el-radio-group {
  font-size: 17px;
  margin: 10px 0px 20px 0px;
}

#CreateBlog .el-checkbox-group {
  margin: 10px 0px 20px 0px;
}

#CreateBlog .el-checkbox-group .el-checkbox {
  font-size: 17px;
  margin-bottom: 6px;
}

#CreateBlog .el-upload {
  margin-top: 10px;
}
</style>
